import { ref, onBeforeUnmount } from "vue";

export type ClearTimer = () => void;

export type SetTimer = (handler: () => void, timeout: number) => void;

/**
 * 使用定时器
 * @param autoClear 是否在生命周期结束前自动清除定时器
 */
export const useTimeout = (autoClear = true): [SetTimer, ClearTimer] => {
  const timer = ref(undefined as unknown as number);

  const clearTimer: ClearTimer = () => {
    if (timer.value) {
      clearTimeout(timer.value);
      timer.value = undefined as unknown as number;
    }
  };

  const setTimer: SetTimer = (handler, timeout) => {
    clearTimer();
    timer.value = setTimeout(handler, timeout) as unknown as number;
  };

  if (autoClear) {
    onBeforeUnmount(clearTimer);
  }

  /** 页面可能存在多个定时器 不使用对象返回 调用时自主命名形参 */
  return [setTimer, clearTimer];
};
